<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\Order;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Services\OrderNumberGenerator;
use App\Models\Province;
use App\Models\City;
use App\Models\District;
use App\Services\CartService;
use App\Services\StockService;
use App\Services\OrderService;
use App\Services\ProductService;
use App\Services\PriceCalculationService;
use App\Services\CheckoutService;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Requests\CreateOrderRequest;
use App\Http\Requests\CancelOrderRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class OrderController extends Controller
{
    protected OrderService $orderService;
    protected ProductService $productService;
    protected CheckoutService $checkoutService;

    public function __construct(
        OrderService $orderService, 
        ProductService $productService,
        CheckoutService $checkoutService
    ) {
        $this->orderService = $orderService;
        $this->productService = $productService;
        $this->checkoutService = $checkoutService;
    }
    /**
     * 显示结算页面（从购物车）
     */
    public function checkout(Request $request)
    {
        // 检查来源参数，如果是从购物车来的，清除立即购买的 session
        if ($request->has('from') && $request->get('from') === 'cart') {
            $request->session()->forget(['buy_now_item', 'buy_now_summary']);
        }
        
        // 检查是否是立即购买
        $buyNowItem = $request->session()->get('buy_now_item');
        
        if ($buyNowItem) {
            // 立即购买流程 - 重新计算价格确保数据正确
            $priceCalculationService = app(PriceCalculationService::class);
            $result = $priceCalculationService->calculateBuyNowPrice($buyNowItem, null);
            
            if ($result['success']) {
                $summary = $result['data'];
            } else {
                // 如果计算失败，使用 session 中的数据作为备用
                $summary = $request->session()->get('buy_now_summary', [
                    'subtotal' => 0,
                    'shipping' => 0,
                    'discount' => 0,
                    'total' => 0
                ]);
            }
            
            $items = [$buyNowItem];
            $isBuyNow = true;
        } else {
            // 购物车结算流程
            $cartService = new CartService();
            $userId = auth()->id();
            
            // 优先使用用户ID查找购物车，确保找到正确的购物车
            $cart = $cartService->getOrCreateCart($userId, null);
            $cart->load(['items.product', 'items.variant']);
            
            // 获取选中的商品（只结算选中的商品）
            $selectedItems = $cart->items->where('is_selected', true);
            
            // 如果没有选中商品，重定向到购物车页面
            if ($selectedItems->isEmpty()) {
                return redirect()->route('cart')->with('error', '请选择要结算的商品');
            }
            
            // 准备结算数据（只包含选中的商品）
            $items = $selectedItems->map(function ($item) {
                return [
                    'id' => $item->id,
                    'product_id' => $item->product_id,
                    'variant_id' => $item->variant_id,
                    'name' => $item->product->name,
                    'image' => $item->image ?: ($item->product->images[0]->image_path ?? '/images/placeholder.jpg'),
                    'specs' => $item->specifications,
                    'price' => $item->price,
                    'quantity' => $item->quantity,
                    'subtotal' => $item->subtotal
                ];
            })->toArray();
            
            // 重新计算价格确保数据正确
            $priceCalculationService = app(PriceCalculationService::class);
            $cartItems = $selectedItems->map(function ($item) {
                return [
                    'product_id' => $item->product_id,
                    'variant_id' => $item->variant_id,
                    'quantity' => $item->quantity,
                ];
            })->toArray();
            
            $result = $priceCalculationService->calculateCartPrice($cartItems, null);
            
            if ($result['success']) {
                $summary = $result['data'];
            } else {
                // 如果计算失败，使用购物车数据作为备用
                $summary = [
                    'subtotal' => $cart->selected_subtotal,
                    'shipping' => $cart->shipping_fee,
                    'discount' => $cart->discount,
                    'total' => $cart->total_amount
                ];
            }
            
            $isBuyNow = false;
        }
        
        // 获取用户地址
        $addresses = auth()->check() 
            ? auth()->user()->addresses()->orderBy('is_default', 'desc')->orderBy('created_at', 'desc')->get()
            : [];
        
        // 获取地址数据（按照Inertia.js推荐方式）
        $provinces = Province::active()->ordered()->select(['id', 'name', 'code'])->get();
        
        // 获取优惠券数据
        $availableCoupons = [];
        $unavailableCoupons = [];
        
        if (auth()->check()) {
            $couponService = new \App\Services\CouponService();
            $orderAmount = $summary['subtotal'];
            
            $coupons = $couponService->getAvailableCoupons(
                auth()->id(),
                $orderAmount,
                $items
            );
            
            $availableCoupons = $coupons['available'] ?? [];
            $unavailableCoupons = $coupons['unavailable'] ?? [];
        }
        
        
        return Inertia::render('Shop/Checkout', [
            'items' => $items,
            'summary' => $summary,
            'addresses' => $addresses,
            'provinces' => $provinces,
            'isBuyNow' => $isBuyNow,
            'availableCoupons' => $availableCoupons,
            'unavailableCoupons' => $unavailableCoupons
        ]);
    }

    /**
     * 获取城市数据（用于地址选择）
     */
    public function getCities(Request $request)
    {
        $request->validate([
            'province_id' => 'required|integer|exists:provinces,id'
        ]);

        $cities = City::active()
            ->byProvince($request->province_id)
            ->ordered()
            ->select(['id', 'name', 'code'])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $cities
        ]);
    }

    /**
     * 获取区县数据（用于地址选择）
     */
    public function getDistricts(Request $request)
    {
        $request->validate([
            'city_id' => 'required|integer|exists:cities,id'
        ]);

        $districts = District::active()
            ->byCity($request->city_id)
            ->ordered()
            ->select(['id', 'name', 'code'])
            ->get();

        return response()->json([
            'success' => true,
            'data' => $districts
        ]);
    }

    /**
     * 立即购买（从商品详情页）
     */
    public function buyNow(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'variant_id' => 'nullable|exists:product_variants,id',
            'quantity' => 'required|integer|min:1',
        ]);

        $product = Product::with('images')->findOrFail($request->product_id);
        $variant = $request->variant_id ? ProductVariant::with('attributeValues.attribute')->findOrFail($request->variant_id) : null;

        // 检查库存
        $stock = $variant ? $variant->stock_quantity : $product->stock_quantity;
        if ($stock < $request->quantity) {
            return redirect()->back()->with('error', '库存不足');
        }

        // 准备商品信息
        $price = $this->productService->getProductPrice($product, $variant);
        
        // 根据商品类型处理规格信息
        if ($product->product_type === 'single') {
            // 单规格商品，不设置规格信息
            $specifications = [];
        } else {
            // 多规格商品，从变体获取规格信息
            $specifications = $variant ? $this->productService->getVariantSpecifications($variant) : [];
        }
        
        $image = $this->productService->getProductImage($product, $variant);

        $item = [
            'product_id' => $product->id,
            'variant_id' => $variant?->id,
            'name' => $product->name,
            'image' => $image,
            'specs' => $specifications,
            'price' => $price,
            'quantity' => $request->quantity,
            'subtotal' => $price * $request->quantity
        ];

        // 计算总价
        $subtotal = $price * $request->quantity;
        $shipping = $subtotal >= 1000 ? 0 : 50;
        $discount = 0;
        $total = $subtotal + $shipping - $discount;

        // 将数据存储到 session 中
        $request->session()->put('buy_now_item', $item);
        $request->session()->put('buy_now_summary', [
            'subtotal' => $subtotal,
            'shipping' => $shipping,
            'discount' => $discount,
            'total' => $total
        ]);

        return redirect()->route('checkout');
    }

    /**
     * 计算价格（选择优惠券后）
     * 使用价格计算服务处理
     */
    public function calculatePrice(Request $request, PriceCalculationService $priceCalculationService)
    {
        try {
            $userId = auth()->id();
            $sessionId = $request->session()->getId();
            $userCouponId = $request->input('user_coupon_id');
            
            // 检查是否是立即购买
            $buyNowItem = $request->session()->get('buy_now_item');
            
            if ($buyNowItem) {
                // 立即购买流程
                $result = $priceCalculationService->calculateBuyNowPrice($buyNowItem, $userCouponId);
            } else {
                // 购物车结算流程
                $cartService = new CartService();
                $cart = $cartService->getOrCreateCart($userId, $sessionId);
                $cart->load(['items.product', 'items.variant']);
                
                $selectedItems = $cart->items->where('is_selected', true);
                
                if ($selectedItems->isEmpty()) {
                    return response()->json([
                        'success' => false,
                        'message' => '请选择要结算的商品'
                    ], 400);
                }
                
                // 准备购物车商品数据
                $cartItems = $selectedItems->map(function ($item) {
                    return [
                        'product_id' => $item->product_id,
                        'variant_id' => $item->variant_id,
                        'quantity' => $item->quantity,
                    ];
                })->toArray();
                
                $result = $priceCalculationService->calculateCartPrice($cartItems, $userCouponId);
            }
            
            if ($result['success']) {
                // 更新 session 中的价格数据（立即购买时）
                if ($buyNowItem) {
                    $request->session()->put('buy_now_summary', $result['data']);
                }
                return response()->json($result);
            } else {
                return response()->json($result, 400);
            }
            
        } catch (\Exception $e) {
            \Log::error('Price calculation failed', [
                'user_id' => auth()->id(),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '价格计算失败'
            ], 500);
        }
    }

    /**
     * 提交订单
     */
    public function submit(CreateOrderRequest $request)
    {
        try {
            $userId = auth()->id();
            
            // 判断是从购物车结算还是立即购买
            $buyNowItem = $request->session()->get('buy_now_item');
            
            if ($buyNowItem) {
                // 立即购买流程
                $order = $this->checkoutService->createOrderFromBuyNow($request->validated(), $userId);
                
                // 清除 session
                $request->session()->forget(['buy_now_item', 'buy_now_summary']);
            } else {
                // 购物车结算流程
                $order = $this->checkoutService->createOrderFromCart($request->validated(), $userId);
            }

            // 跳转到支付页面
            return redirect()->route('payment.show', $order->order_number)
                ->with('success', '订单创建成功，请完成支付');
            
        } catch (\Exception $e) {
            \Log::error('Order submission failed', [
                'user_id' => auth()->id(),
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->except(['_token'])
            ]);
            return redirect()->back()->with('error', '订单提交失败：' . $e->getMessage());
        }
    }



    /**
     * 显示订单详情
     */
    public function show(string $orderNumber): Response
    {
        $order = $this->orderService->getOrderDetails($orderNumber);
        
        $this->authorize('view', $order);
        
        return Inertia::render('Shop/OrderDetail', [
            'order' => $order
        ]);
    }

    /**
     * 显示订单列表（支持筛选和搜索）
     */
    public function index(Request $request): Response
    {
        $orders = $this->orderService->getOrdersForUser(auth()->id(), $request->only(['status', 'keyword']));
            
        return Inertia::render('Shop/Orders', [
            'orders' => $orders,
            'filters' => [
                'status' => $request->status ?? '',
                'keyword' => $request->keyword ?? ''
            ]
        ]);
    }

    /**
     * 用户取消订单
     */
    public function userCancel(CancelOrderRequest $request, string $orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        $this->authorize('cancel', $order);

        try {
            $this->orderService->cancelOrder($order, $request->reason ?? '用户取消');

            return redirect()->back()->with('success', '订单已取消');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 确认收货
     */
    public function confirmDelivery(string $orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->firstOrFail();
        
        $this->authorize('confirmDelivery', $order);

        try {
            $this->orderService->confirmDelivery($order);

            return redirect()->back()->with('success', '已确认收货');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
